import React, { Component } from 'react';
import { Tabs } from 'antd-mobile';
import HomeAlbumList from '../components/HomeAlbumList'
import { getDeviceId } from '../utils';
import '../css/HomePage.css'

/**
 * 专辑列表
 */
class CategoryTabs extends Component {
	constructor(props) {
		super(props);
		this.albumItemClick = this.albumItemClick.bind(this);
		this.handleScroll = this.handleScroll.bind(this);

		const location = this.props.location;
		let category = location.category;
		const device_id = getDeviceId();
		if (location.category) {
			sessionStorage.setItem('category', category);
		} else {
			category = parseInt(sessionStorage.getItem('category'), 10) || 0;
		}
		const categorys = JSON.parse(localStorage.getItem('category_list'));
		this.state = {
			categorys: categorys,
			category: category,
			device_id: device_id,
		};
	}

	componentDidMount() {
		window.addEventListener('scroll', this.handleScroll);
	}

	handleScroll(event) {
		event.stopPropagation();
	}

	componentWillUnmount() {
		window.removeEventListener('scroll', this.handleScroll);
	}

	showCategory(item, index) {
		return (
			<div key={index}>
				<HomeAlbumList
					category_id={item.category_id}
					device_id={this.state.device_id}
					albumItemClick={this.albumItemClick}>
				</HomeAlbumList>
			</div>
		)
	}

	albumItemClick(album) {
		this.props.history.push({
			pathname: '/album',
			device_id: this.state.device_id,
			album: album
		});
	}

	tabOnChange(tab, index) {
		sessionStorage.setItem('category', index);
		sessionStorage.setItem('scrollY', 0);
	}

	render() {
		return (
			<div>
				<Tabs
					tabs={this.state.categorys}
					swipeable={false}
					initialPage={this.state.category}
					useOnPan={false}
					tabBarActiveTextColor="#15a67c"
					tabBarInactiveTextColor="#9E9E9E"
					tabBarUnderlineStyle={styles.line}
					onChange={this.tabOnChange.bind(this)}>
					{
						this.state.categorys.map(this.showCategory.bind(this))
					}
				</Tabs>
			</div>
		);
	}
}
export default CategoryTabs;

const styles = {
	home: {
		width: '100%',
		height: '100%',
		position: 'fixed',
		zIndex: 1,
		top: 0,
	},
	line: {
		borderColor: '#15a67c',
		height: '1px',
	},
}